package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.News;
import cn.wolfcode.trip.base.query.NewsQueryObject;
import cn.wolfcode.trip.base.service.INewsService;
import cn.wolfcode.trip.base.service.INewsTypeService;
import cn.wolfcode.trip.base.util.JSONResult;
import cn.wolfcode.trip.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author 不出bug- 么么哒
 * @DESCRIPTION
 * @create 2018/11/13
 */
@Controller
@RequestMapping("/news")
public class NewsController {
    @Autowired
    private INewsService newsService;
    @Autowired
    private INewsTypeService newsTypeService;

    @RequestMapping("/list")
    public String list(@ModelAttribute("qo") NewsQueryObject qo, Model model) {
        qo.setOrderBy ("newsTime desc");
        model.addAttribute ("pageInfo", newsService.query (qo));
        model.addAttribute ("types", newsTypeService.list ());
        return "/news/list";
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(News entity, MultipartFile img) {
        if (img != null && img.getContentType ().startsWith ("image") && img.getSize () > 0) {
            String url = UploadUtil.upload (img);
            entity.setCoverUrl (url);
        }
        JSONResult result = new JSONResult ();
        try {
            newsService.saveOrUpdate (entity);
        } catch (Exception e) {
            result.mark (e.getMessage ());
        }
        return result;
    }

    @RequestMapping(value = "/getContentById", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getContentById(Long id) {
        return newsService.getContentById (id);
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(Long id) {
        JSONResult result = new JSONResult ();
        try {
            newsService.delete (id);
        } catch (Exception e) {
            result.mark (e.getMessage ());
        }
        return result;
    }
}
